package com.atlin.project.controller;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.SysNotification;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.domain.SysNotification;
import com.atlin.project.model.dto.sysNotification.SysNotificationQueryRequest;
import com.atlin.project.model.dto.sysNotification.SysNotificationUpdateRequest;
import com.atlin.project.model.enums.sys.SysNotificationStatusEnum;
import com.atlin.project.service.SysNotificationService;
import com.atlin.project.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 模版接口
 *
 * @author atlin
 */
@RestController
@RequestMapping("/sysNotification")
public class SysNotificationController {

    @Resource
    private SysNotificationService sysNotificationService;

    @Resource
    private SysUserService sysUserService;

    private final static Gson GSON = new Gson();

    // region 增删改查


    /**
     * 标为已读
     *
     * @param sysNotificationUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateSysNotification(@RequestBody SysNotificationUpdateRequest sysNotificationUpdateRequest, HttpServletRequest request) {
        if (sysNotificationUpdateRequest == null || sysNotificationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        long id = sysNotificationUpdateRequest.getId();

        // 判断是否存在
        SysNotification oldsysNotification = sysNotificationService.getById(id);
        ThrowUtils.throwIf(oldsysNotification == null, ErrorCode.NULL_ERROR);

        // 判断是否为自己的通知
        ThrowUtils.throwIf(!loginUser.getId().equals(oldsysNotification.getUserId()), ErrorCode.NO_AUTH_ERROR);

        SysNotification sysNotification = new SysNotification();
        sysNotification.setId(id);
        //标为已读
        sysNotification.setStatus(SysNotificationStatusEnum.QUEUEING.getValue());


        boolean result = sysNotificationService.updateById(sysNotification);
        return ResultUtils.success(result);
    }

    /**
     * 将所有未读标为已读
     *
     * @param request
     * @return
     */
    @PostMapping("/update/all")
    public BaseResponse<Boolean> updateAllSysNotification(HttpServletRequest request) {
        SysUser loginUser = sysUserService.getLoginUser(request);

        UpdateWrapper<SysNotification> updateWrapper = new UpdateWrapper<>();

        // 所有未读消息标记为已读
        updateWrapper.lambda().eq(SysNotification::getUserId, loginUser.getId())
                .eq(SysNotification::getStatus, SysNotificationStatusEnum.FAILURE.getValue())
                .set(SysNotification::getStatus, SysNotificationStatusEnum.QUEUEING.getValue());

        boolean result = sysNotificationService.update(updateWrapper);

        return ResultUtils.success(result);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSysNotification(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        SysNotification oldsysNotification = sysNotificationService.getById(id);
        ThrowUtils.throwIf(oldsysNotification == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可删除
        if (!oldsysNotification.getUserId().equals(user.getId()) && !sysUserService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = sysNotificationService.removeById(id);
        return ResultUtils.success(b);
    }


    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<SysNotification> getSysNotificationById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysNotification sysNotification = sysNotificationService.getById(id);
        if (sysNotification == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!sysNotification.getUserId().equals(loginUser.getId()) && !sysUserService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(sysNotification);
    }


    /**
     * 分页获取列表（仅管理员）
     *
     * @param sysNotificationQueryRequest 查询参数
     * @param request                     查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<SysNotification>> listSysNotificationByPage(@RequestBody SysNotificationQueryRequest sysNotificationQueryRequest,
                                                                         HttpServletRequest request) {
        long current = sysNotificationQueryRequest.getCurrent();
        long size = sysNotificationQueryRequest.getPageSize();
        Page<SysNotification> sysNotificationPage = sysNotificationService.page(new Page<>(current, size),
                sysNotificationService.getQueryWrapper(sysNotificationQueryRequest));
        return ResultUtils.success(sysNotificationPage);
    }

    /**
     * 查询我的通知信息
     *
     * @param sysNotificationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/my/page")
    public BaseResponse<Page<SysNotification>> listMySysNotificationByPage(@RequestBody SysNotificationQueryRequest sysNotificationQueryRequest,
                                                                           HttpServletRequest request) {
        long current = sysNotificationQueryRequest.getCurrent();
        long size = sysNotificationQueryRequest.getPageSize();

        SysUser loginUser = sysUserService.getLoginUser(request);

        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        sysNotificationQueryRequest.setUserId(loginUser.getId());

        Page<SysNotification> sysNotificationPage = sysNotificationService.page(new Page<>(current, size),
                sysNotificationService.getQueryWrapper(sysNotificationQueryRequest));
        return ResultUtils.success(sysNotificationPage);
    }

    // endregion

}
